import os
import sys
import logging
from logsMultiHandler import MultiprocessHandler
from readConfig import ReadConfig
from pathlib import Path, PureWindowsPath


def loggerDefine(platform, log_name):
    """

    :param platform:  功能模块名称
    :param log_name: 日志文件
    :return:
    """
    """
     读取配置文件
    """
    logout=0
    try:
        conf = ReadConfig()
        logout = conf.get_host("log", "logout")

    except:
        pass

    # 基本路径
    base_dir = ".\\log"
    # I've explicitly declared my path as being in Windows format, so I can use forward slashes in it.
    info_dir_path_base = PureWindowsPath(base_dir + "\\info\\{}".format(platform))
    error_dir_path_base = PureWindowsPath(base_dir + "\\error\\{}".format(platform))

    # Convert path to the right format for the current operating system
    info_dir_path = Path(info_dir_path_base)
    error_dir_path = Path(error_dir_path_base)


    # 判断响应的文件是否存在
    if not os.path.exists(info_dir_path):
        os.makedirs(info_dir_path)
    info_dir = os.path.join(info_dir_path, log_name)

    if not os.path.exists(error_dir_path):
        os.makedirs(error_dir_path)
    error_dir = os.path.join(error_dir_path, log_name)

    # 返回一个logger对象，如果没有指定名字将返回root logger
    log = logging.getLogger(log_name)
    # 防止重复输出日志
    if not log.handlers:
        """
         level_relations = {
            'debug': logging.DEBUG,
            'info': logging.INFO,
            'warning': logging.WARNING,
            'error': logging.ERROR,
            'crit': logging.CRITICAL
        }  # 日志级别关系映射
        """
        # 设置日志级别
        log.setLevel("INFO")
        # 定义日志输出格式
        # formattler = '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
        # formattler = '%(asctime)s - %(processName)s - %(threadName)s - %(levelname)s|%(filename)s:%(lineno)d|%(funcName)s|%(message)s'
        formattler = '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
        fmt = logging.Formatter(formattler)

        # 设置控制台文件输出
        log_handler_info = MultiprocessHandler(info_dir)
        log_handler_err = MultiprocessHandler(error_dir)

        # 设置日志输出格式：
        log_handler_info.setFormatter(fmt)
        log_handler_err.setFormatter(fmt)

        # 设置过滤条件
        info_filter = logging.Filter()
        info_filter.filter = lambda record: record.levelno < logging.WARNING  # 设置过滤等级
        err_filter = logging.Filter()
        err_filter.filter = lambda record: record.levelno >= logging.WARNING

        # 对文件输出日志添加过滤条件
        log_handler_info.addFilter(info_filter)
        log_handler_err.addFilter(err_filter)

        # 对logger增加handler日志处理器
        log.addHandler(log_handler_info)
        log.addHandler(log_handler_err)

        # 设置日志控制台输出
        # 控制日志是否输出到屏幕
        if int(logout) == 1:
            stream_handler = logging.StreamHandler(sys.stdout)
            stream_handler.setLevel(logging.INFO)
            # 设置日志输出格式：
            stream_handler.setFormatter(fmt)
            log.addHandler(stream_handler)

        return log


if __name__ == '__main__':
    logg = loggerDefine("youtube", "youtube.log")
    logg.info("info")
    logg.warning("warning")
    logg.error("error")
